package com.gugee.tiktok.deploy.consumer.music.controller;


import com.gugee.tiktok.common.model.spider.music.MusicResponse;
import com.gugee.tiktok.data.common.msg.MusicMessage;
import com.gugee.tiktok.data.consumer.music.core.service.MusicService;
import com.xiguaji.boot.toolkit.JsonUtil;
import com.xiguaji.boot.toolkit.jdbc.JdbcTemplateHelper;
import lombok.val;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
//@RequestMapping("config")
public class NacosConfigControllerTest {

    @Autowired
    MusicService musicService;

    @Autowired
    @Qualifier("kafkaTemplateMusic")
    private KafkaTemplate<Long, MusicMessage> kafkaTemplateMusic;

    @Autowired
    RestHighLevelClient highLevelClient;

    @RequestMapping(path = "/send")
    public void sendFoo() throws IOException {
        SearchRequest searchRequest = new SearchRequest("music_idx");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.sort("userGrowth", SortOrder.DESC);
        searchSourceBuilder.from(0);
        searchSourceBuilder.size(1);
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = highLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        val hits = searchResponse.getHits().getHits();
        List<Long> musics = new ArrayList<>();

        for (SearchHit hit : hits) {
            Map music = JsonUtil.jsonParse(Map.class,hit.getSourceAsString());
            musics.add(Long.parseLong(music.get("mid").toString()));
        }

        // List<Map<String,Object>> musics = JdbcTemplateHelper.select("select * from music order by user_count desc limit 0,1");
        List<MusicMessage> musicMessageList = new ArrayList<>();

        musics.forEach( m ->{
            MusicMessage musicMessage = new MusicMessage();
            musicMessage.setMid(m);
            musicMessageList.add(musicMessage);
        });

        musicService.updateMusic(musicMessageList);
    }

}
